# coding=utf-8
import  sys
user_action_data="E:\\八斗\\res_system_data\\user_watch_pref.sml"
music_meta_data="E:\\八斗\\res_system_data\\music_meta"
user_profile_data="E:\\八斗\\res_system_data\\user_profile.data"
megre_data = "..\\data\\megre.data"

def read_context_from_file(path):
    with open(path,"r",encoding="utf-8") as fd_r:
        line_list = fd_r.readlines()
    return line_list

def decode_music_meta_data(path):
    iteminfo_dict = {}
    line_list = read_context_from_file(path)
    for line in line_list:
        ss = line.strip().split("\001")
        if len(ss) != 6:
            continue
        itemid, name, desc, total_timelen, location, tags = ss
        iteminfo_dict[itemid] = "\001".join([name,desc, total_timelen, location, tags])

    return iteminfo_dict

def decode_user_profile_data(path):
    user_profile_dict = {}
    line_list = read_context_from_file(path)
    for line in line_list:
        ss = line.strip().split(",")
        if len(ss) != 5:
            continue

        userid, gender, age, salary, location = ss

        user_profile_dict[userid.strip()] = "\001".join([gender.strip(), age, salary, location])

    return user_profile_dict

def decode_user_action_data(path,user_profile_dict,iteminfo_dict):
    line_list = read_context_from_file(path)
    new_line_list = []
    for line in line_list:
        ss = line.strip().split("\001")
        if len(ss) != 4:
            continue

        userid, itemid, watchlen, hours = ss
        if userid not in user_profile_dict:
            continue
        if itemid not in iteminfo_dict:
            continue

        line = "\001".join([userid, itemid, watchlen, hours,user_profile_dict[userid],iteminfo_dict[itemid]]) + "\n"

        new_line_list.append(line)

        # write_context_to_file(megre_data,line)
        # write_context_to_file(megre_data, "\n")
    return new_line_list

def write_context_to_file(path,line_list):
    with open(path,"w",encoding="utf-8") as fd_w:
        fd_w.writelines(line_list)


if __name__ == '__main__':

    user_profile_dict = decode_user_profile_data(user_profile_data)
    # print(user_profile_dict)
    iteminfo_dict = decode_music_meta_data(music_meta_data)
    #print(iteminfo_dict)
    line_list = decode_user_action_data(user_action_data,user_profile_dict,iteminfo_dict)
    # print(line_list)
    write_context_to_file(megre_data,line_list)